
import pandas as pd
import numpy as np
from keras.layers import Embedding, Conv1D, GlobalMaxPooling1D, Dense
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras_preprocessing.sequence import pad_sequences
from sklearn.preprocessing import LabelEncoder

# 从CSV文件中读取数据
data = pd.read_csv('data1.csv')

# 提取文本和标签列
text = data['review'].values
labels = data['label'].values

# 创建标签编码器
label_encoder = LabelEncoder()

# 对标签进行编码
labels = label_encoder.fit_transform(labels)

# 对文本进行分词和编码
tokenizer = Tokenizer(num_words=5000)
tokenizer.fit_on_texts(text)
sequences = tokenizer.texts_to_sequences(text)

# 对文本序列进行填充
max_len = max([len(seq) for seq in sequences])
sequences = pad_sequences(sequences, maxlen=max_len)

# 定义模型结构
embedding_dim = 50
filters = 64
kernel_size = 5
hidden_dims = 128
num_classes = len(np.unique(labels))

model = Sequential()
model.add(Embedding(5000, embedding_dim, input_length=max_len))
model.add(Conv1D(filters, kernel_size, activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(hidden_dims, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

# 加载训练好的模型权重
model.load_weights('emotion_model.h5')

# 定义情绪标签与其对应的名称
label_mapping = {0: '高兴', 1: '生气', 2: '厌恶', 3: '伤心',4:'惊讶',5:"害怕"}

def keras_word(new_text):
    new_sequences = tokenizer.texts_to_sequences(new_text)
    new_sequences = pad_sequences(new_sequences, maxlen=max_len)

    # 预测情绪
    predictions = model.predict(new_sequences)
    predicted_label = np.argmax(predictions[0])
    predicted_emotion = label_mapping[predicted_label]

    # 打印预测结果
    return(predicted_emotion)

if __name__ == "__main__":
    print('预测情绪:\t'+keras_word("伤心"))